﻿namespace System.Web
{
    internal class NetHttpApplicationStateLock : ReadWriteObjectLock
    {
        private int _recursionCount;
        private int _threadId;

        internal NetHttpApplicationStateLock() { }

        internal override void AcquireRead()
        {
            int currentThreadId = GetCurrentThreadId();
            if (_threadId != currentThreadId)
                base.AcquireRead();
        }

        internal override void AcquireWrite()
        {
            int currentThreadId = GetCurrentThreadId();
            if (_threadId == currentThreadId)
                _recursionCount++;
            else
            {
                base.AcquireWrite();
                _threadId = currentThreadId;
                _recursionCount = 1;
            }
        }

        internal void EnsureReleaseWrite()
        {
            int currentThreadId = GetCurrentThreadId();
            if (_threadId == currentThreadId)
            {
                _threadId = 0;
                _recursionCount = 0;
                base.ReleaseWrite();
            }
        }

        internal override void ReleaseRead()
        {
            int currentThreadId = GetCurrentThreadId();
            if (_threadId != currentThreadId)
                base.ReleaseRead();
        }

        internal override void ReleaseWrite()
        {
            int currentThreadId = GetCurrentThreadId();
            if ((_threadId == currentThreadId) && (--_recursionCount == 0))
            {
                _threadId = 0;
                base.ReleaseWrite();
            }
        }

        internal static int GetCurrentThreadId() { return 0; }
    }
}
